<template>
  <div class="diary-editor">
    <div class="diary-editor_form">
      <div class="diary-editor_top">
        <input type="text" class="diary-editor_title" placeholder="请输入标题" v-model="diaryForm.title" />
        <yk-popover placement="bottomRight" title="选择天气">
          <template #content>
            <yk-space wrap :size="[36, 16]" style="padding: 16px 0 12px 16px;">
              <div class="diary-editor_weather" v-for="item in weather"
                :class="{ selected: diaryForm.weather_id === item.id }">
                <img :src="`${item.icon}`" style="width: 20px;height: 20px;"
                  @click="selectWeather(item.id)">
              </div>

            </yk-space>
          </template>
          <img :src="weatherUrl" style="width: 20px;height: 20px;" />
        </yk-popover>
      </div>
      <yk-text-area v-model="diaryForm.content" :max-lenght="1600" placeholder="请输入..."
        :auto-size="{ minRows: 24, maxRows: 24 }"></yk-text-area>
      <div class="diary-editor_pictrue">
        <!-- 上传图片,限制最多4张 -->
        <yk-upload :upload-url="uploadUrl" :file-list="Array.isArray(diaryForm.picture) ? diaryForm.picture : []" accept="image/*" :limit="4"
          @handleSuccess="handleUploadSuccess" @handleDelete="deletePicture"></yk-upload>
      </div>
    </div>
    <div class="diary-editor_foot">
      <yk-space size="s">
        <yk-button type="secondary" @click="reset">重置</yk-button>
        <yk-button @click="newDiary">新建笔记</yk-button>
      </yk-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed,getCurrentInstance } from 'vue'
import { weather } from '../../utils/weather'
import type { diaryData } from '../../utils/interface'
import type { fileData } from '../../utils/interface';
import { baseUrl } from '../../utils/env';
import { useCode } from '../../hooks/codeHook';
import { useFile } from '../../hooks/fileHook';
import { useUserStore } from '../../stores/user';
import { addDiaryApi } from '../../api/diary-api';
import { getTimeYMDHMS } from '../../utils/time';
const userStore = useUserStore();
const {tackleCode} = useCode();
  const proxy: any = getCurrentInstance()?.proxy;


//上传文件的接口地址
const uploadUrl = `${baseUrl}/api/file/upload`;
//文件地址列表
const fileUrlList = ref<{ id: number, url: string }[]>([])

const diaryForm = ref<diaryData>({ 
  title: '', 
  created_at: '',
  content: '',
  weather_id: 0 })
//获取天气url
const weatherUrl = computed(() => {
    return weather[diaryForm.value.weather_id].icon
})
//选择天气
const selectWeather = (id: number) => {
  diaryForm.value.weather_id = id;
}

//新建日记,添加日记
const emit = defineEmits(['getData']);
const newDiary = async () => {
  if( fileUrlList.value.length > 0){
     diaryForm.value.picture =JSON.stringify(fileUrlList.value)
  }
  diaryForm.value.created_at = getTimeYMDHMS(new Date())
  let request = {
    token: userStore.token,
    value: diaryForm.value
  }
  try {
    const res = await addDiaryApi(request);
    if(tackleCode(res.data.code)){
      diaryForm.value = { title: '', created_at: '', content: '', weather_id: 0 }
      fileUrlList.value = []
      proxy.$message({ type: "success", message: "新建成功" });
      // 新建成功后刷新日记列表
      emit('getData')
    }
  } catch (error) {
    proxy.$message({ type: "error", message: "新建失败" });
    console.error('新建日记失败:', error)
  }
}

//重置
const reset = () => {
  diaryForm.value = { title: '', created_at: '', content: '', weather_id: 0 }
  fileUrlList.value = []
}

//删除
const { deleteFile } = useFile();
const deletePicture = (e: any) => {
  //后端删除
  deleteFile(e);
  //前端删除
  fileUrlList.value.splice(e[0], 1)
}
//图片提交成功
const handleUploadSuccess = (res: { code: number, data: fileData }) => {
  if (tackleCode(res.code)) {
    let fileData = res.data
    let photo = {
      id: fileData.id, // 文件id
      url: fileData.url, // 文件路径
    }
    fileUrlList.value.push(photo)
  }
}


</script>

<style scoped lang="less">
.diary-editor {
  width: 100%;
  background-color: @bg-color-l;
  border-radius: @radius-m;

  &_form {
    padding: @space-xl;

    .selected {
      &::before {
        position: absolute;
        bottom: -6px;
        left: 7px;
        content: '';
        display: block;
        width: 6px;
        height: 6px;
        border-radius: 4px;
        background: @pcolor;
      }
    }

    input {
      //去除input的默认边框
      border: none;
      //去除选中后的默认边框
      background: transparent;
      outline: none;

      &::placeholder {
        color: @font-color-s;
      }
    }
  }

  &_top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &_title {
    font-size: @size-xl;
    font-weight: bold;
    color: @font-color-l;
    padding-bottom: @space-m;
  }

  &_pictrue {
    padding-top: @space-m;
  }

  &_foot {
    padding: @space-m;
    display: flex;
    justify-content: end;
    border-top: 1px solid @line-color-s ;
  }

  :deep(.yk-text-area) {
    background-color: transparent;
    border: none;
    border-radius: 0;
    padding: 0;

  }

  :deep(.yk-text-area_inner) {
    font-size: @size-m;
    line-height: 1.5;

    &::placeholder {
      color: @gray-5;
    }
  }
}
</style>